<?php

// 登录
// POST member.login

namespace app\api\resource\member;
use think\Db;
use think\facade\Session;
use think\facade\Cache;
use app\common\validate\Member as MemberValidate;

class Login
{
    // 方法
    public $_method = ['POST'];
    // 前置
    public $_pre    = [];
    // 描述
    public $_description = '登录';
    // 参数
    public $_param  = [
        'mobile'   => '手机号',
        'password' => '登录密码',
    ];

    public function run(&$request)
    {
        $params   = $request->param();
        $validate = new MemberValidate;
        if ( !$validate->scene('login')->check($params) ) {
            $errMsg = $validate->getError();
            return [422,$errMsg];
        }

        $member = Db::name('member')->where('mobile',$params['mobile'])
                                    ->where( 'password',md5($params['password']) )
                                    ->field('password',true)
                                    ->find();

        if ( is_null($member) )     return [401,'用户名或密码错误'];
        if (1 == $member['status']) return [423,'帐号别限制使用'];
        
        $device = $request->param('device/s','','trim');
        if ( empty($device) ) return [422,'设备ID必须'];
          
        Cache::set('device_' . $params['mobile'],$device,0);
        
        // p($member);die;

        // 写入Session
        Session::set('member',$member);

        return [201,'登录成功'];
    }
}